//
//  BERxObservableExtension.swift
//  BasicExtensions
//
//  Created by 范晓鑫 on 2023/1/28.
//

import RxSwift

extension Completable {
    /// 直接生成完成事件
    public static var completed: Self {
        return .create { ob in
            ob(.completed)
            return Disposables.create {}
        }
    }
    /// 直接生成错误事件
    public static func error(_ error: Error) -> Self {
        return .create { ob in
            ob(.error(error))
            return Disposables.create {}
        }
    }
}

/// 改变的值
private enum BERxChanged<Element> {
    /// 未设置值
    case none
    /// 初始值
    case starts(Element)
    /// 有变化
    case changed(old: Element, new: Element)
}
extension ObservableType {
    /// 当值有变化时发送消息(重复值也算，若不要重复则在此之前先调用distinctUntilChanged)
    public func changed() -> Observable<(old: Element, new: Element)> {
        let seed: BERxChanged<Element> = .none
        return self.scan(seed) { changed, element in
            switch changed {
            case .none: return .starts(element)
            case .starts(let old): return .changed(old: old, new: element)
            case .changed(_, let old): return .changed(old: old, new: element)
            }
        }.compactMap { changed in
            if case .changed(let old, let new) = changed {
                return (old: old, new: new)
            } else {
                return nil
            }
        }
    }
}
